<template>
  <div class="main">
    <mine-title>用户管理</mine-title>
    <div class="content">
      <div class="block-header">
        <div class="block-header-left">
          <mine-button type="primary" @click="addUser()"
            ><i class="iconfont icon-add-line"></i>新建用户
            <!-- v-if="hasAuth('system:user:add')" -->
          </mine-button>
          <mine-button
            @click="deleteUser"
            secondary
            :disabled="!multipleSelection.length"
            ><i class="iconfont icon-delete-line"></i>删除
            <!-- v-if="hasAuth('system:user:delete')" -->
          </mine-button>
          <mine-button type="primary" secondary @click="loadData()"
            ><i class="iconfont icon-reset-line"></i>刷新
          </mine-button>
        </div>
        <div class="block-header-right"></div>
      </div>
      <el-table
        class="table"
        :data="tableData"
        style="width: 100%"
        v-loading="loading"
        @selection-change="handleSelectionChange"
        ref="multipleTable"
      >
        <el-table-column type="selection" width="45"></el-table-column>
        <el-table-column label="序号" show-overflow-tooltip width="60">
          <template slot-scope="scope">
            <span>{{ scope.$index + (currentPage - 1) * pageSize + 1 }} </span>
          </template>
        </el-table-column>
        <el-table-column label="用户名" prop="username" show-overflow-tooltip>
          <template slot="header">
            <span>用户名</span>
            <mine-table-search
              @searchSubmit="searchSubmit"
              name="username"
            ></mine-table-search>
          </template>
        </el-table-column>
        <el-table-column label="拥有角色" prop="roles" show-overflow-tooltip>
          <template v-slot="scope">
            <el-tag
              size="small"
              type="warning"
              v-for="(item, index) in scope.row.sysRoleList"
              :key="index"
            >
              {{ item.name }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="状态" prop="status" show-overflow-tooltip>
          <template v-slot="{ row }">
            <el-switch
              v-model="row.status"
              @change="statusChangeHandle(row)"
              active-text="正常"
              inactive-text="禁用"
              active-value="0"
              inactive-value="1"
            ></el-switch>
          </template>
        </el-table-column>
        <!--                <el-table-column label="邮箱" prop="email" show-overflow-tooltip>-->
        <!--                    <template slot="header">-->
        <!--                        <span>邮箱</span>-->
        <!--                        &lt;!&ndash;            <mine-table-search @searchSubmit="searchSubmit" name="modelCount"></mine-table-search>&ndash;&gt;-->
        <!--                    </template>-->
        <!--                </el-table-column>-->
        <!--                <el-table-column label="手机" prop="phonenumber" show-overflow-tooltip>-->
        <!--                    <template slot="header">-->
        <!--                        <span>手机</span>-->
        <!--                        &lt;!&ndash;                  <mine-table-search @searchSubmit="searchSubmit" name="modelCount"></mine-table-search>&ndash;&gt;-->
        <!--                    </template>-->
        <!--                </el-table-column>-->
        <el-table-column
          label="创建时间"
          prop="createTime"
          show-overflow-tooltip
        >
          <template slot="header">
            <span>创建时间</span>
            <!--                  <mine-table-search @searchSubmit="searchSubmit" name="modelCount"></mine-table-search>-->
          </template>
        </el-table-column>
        <el-table-column
          label="最后登录时间"
          prop="loginDate"
          show-overflow-tooltip
        >
          <template slot="header">
            <span>最后登录时间</span>
            <!--                  <mine-table-search @searchSubmit="searchSubmit" name="modelCount"></mine-table-search>-->
          </template>
        </el-table-column>
        <!--                <el-table-column label="备注" prop="remark" show-overflow-tooltip>-->
        <!--                    <template slot="备注">-->
        <!--                        <span>最后登录时间</span>-->
        <!--                        &lt;!&ndash;                  <mine-table-search @searchSubmit="searchSubmit" name="modelCount"></mine-table-search>&ndash;&gt;-->
        <!--                    </template>-->
        <!--                </el-table-column>-->
        <el-table-column label="操作">
          <template slot-scope="scope">
            <mine-button type="text" @click="check(scope.row)"
              >详情
              <!-- v-if="hasAuth('system:user:edit')" -->
            </mine-button>
            <mine-button type="text" @click="handleRoleDialogValue(scope.row)"
              >分配角色
              <!-- v-if="hasAuth('system:user:role')" -->
            </mine-button>
            <el-popconfirm
              title="您确定要对这个用户重置密码吗？"
              @confirm="handleResetPassword(scope.row.id)"
              style="margin-left: 5px"
            >
              <template #reference>
                <mine-button type="text">
                  <!-- v-if="hasAuth('system:user:resetPwd')"  -->
                  重置密码
                </mine-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <mine-pagination
        @numberChange="numberChange"
        :total="total"
        :page-size="listQuery.pageSize"
        :current-page="listQuery.pageNum"
      >
      </mine-pagination>

      <mine-dialog
        :top="'10vh'"
        :appendToBody="true"
        :dialogFormVisible="flag"
        :width="'900px'"
        :modalFlag="modalFlag"
        :title="title"
        :showClose="showClose"
        @close="close"
      >
        <RoleDialog
          slot="option"
          v-model="roleDialogVisible"
          :sysRoleList="sysRoleList"
          :roleDialogVisible="roleDialogVisible"
          :id="id"
          @initUserList="loadData()"
          @close="close"
        ></RoleDialog>
      </mine-dialog>
    </div>
  </div>
</template>
<script>
import requestUtil from "../../utils/authUtil";
import RoleDialog from "./components/roleDialog";
import { detailMixins, modalMixins } from "./mixins.js";

export default {
  components: {
    RoleDialog,
  },
  mixins: [detailMixins, modalMixins],
  data() {
    return {
      sysRoleList: [],
      id: -1,
      listQuery: {
        query: "",
        pageNum: 1,
        pageSize: 10,
      },
      // table参数
      tableData: [],
      total: 0,
      pageSize: 10,
      currentPage: 1,
      multipleSelection: [],
      loading: false,
      tableHeight: window.innerHeight - 330,
      roleDialogVisible: false, // 分配角色弹框
    };
  },
  methods: {
    searchSubmit(value) {
      console.log(value);
      if (value.key === "username") {
        this.listQuery.query = value.value;
      }
      this.loadData(true);
    },
    async loadData(flag) {
      if (flag) {
        this.listQuery.pageNum = 1;
        this.listQuery.pageSize = 10;
        this.currentPage = 1;
      }
      const params = this.listQuery;
      this.loading = true;
      try {
        const res = await this.$store.dispatch(
          "userAdmin/getUserTableList",
          params
        );
        const result = res.data || {};
        // TODO： 定制后台数据处理
        if (result.code === 200) {
          this.tableData = result.userList;
          this.total = result.total;
        } else {
          this.tableData = [];
          this.total = 0;
        }
      } catch (e) {
        console.error(e);
      }
      this.loading = false;
    },
    addUser() {
      this.$router.push({
        path: "/addUser",
      });
    },
    async deleteUser() {
      this.$mineConfirm("确认要删除？", "删除提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const ids = this.multipleSelection.map((item) => item.id);
          this.loading = true;
          try {
            const res = await this.$store.dispatch(
              "userAdmin/deleteUserTable",
              ids
            );
            const result = res.data || {};
            if (result.code == 200) {
              this.$message.success("删除成功!");
              this.loadData(true);
            } else {
              this.$message.error("删除失败");
            }
          } catch (e) {
            console.error(e);
          }
          this.loading = false;
        })
        .catch(() => {});
    },
    // 查看详情
    check(val) {
      this.$router.push({
        path: "/userDetail",
        query: {
          id: val.id,
        },
      });
    },
    hasAuth(perm) {
      let perms = this.$store.getters.GET_PERMS;
      return perms.indexOf(perm) >= 0;
    },
    async handleResetPassword(id) {
      const res = await this.$store.dispatch("userAdmin/resetPassword", id);
      if (res.data.code == 200) {
        this.$message.success("执行成功!");
        await this.loadData();
      } else {
        this.$message.error(res.data.msg);
      }
    },
    handleSelectionChange(selection) {
      this.multipleSelection = selection;
    },
    numberChange(val) {
      switch (val.flag) {
        case "pageSize":
          this.pageSize = val.pageSize;
          this.listQuery.pageNum = 1;
          this.listQuery.pageSize = val.pageSize;
          this.loadData(true);
          break;
        case "currentPage":
          this.currentPage = val.currentPage;
          this.listQuery.pageNum = val.currentPage;
          this.loadData(false);
          break;
        default:
          break;
      }
    },
    async statusChangeHandle(row) {
      let res = await this.$store.dispatch("userAdmin/statusChange", row);
      if (res.data.code == 200) {
        this.$message.success("执行成功！");
      } else {
        this.$message.error("执行失败！");
        await this.loadData();
      }
    },
    handleRoleDialogValue(row) {
      console.log(row);
      this.title = "分配角色";
      this.flag = true;
      this.id = row.id;
      this.sysRoleList = row.sysRoleList;
      this.roleDialogVisible = true;
    },
  },
  created() {
    this.loadData();
  },
};
</script>

<style lang="scss" scoped>
.table {
  margin-top: 15px;
}

.el-tag--small {
  margin-left: 5px;
}
</style>
